<template>
  <Form ref="form" class="xtx-form" tag="form" autocomplete="off" >
    <div class="user-info">
      <img :src="avatar" alt="" />
      <p>Hi，{{ nickname }} 欢迎来小兔鲜，完成绑定后可以QQ账号一键登录哦~</p>
    </div>
    <Field
      tag="div"
      class="xtx-form-item"
      v-slot="{errors}"
      rules="required|mobile"
      name="手机号码"
      ref="mobile"
      :detectInput="false"
    >
      <div class="field">
        <i class="icon iconfont icon-phone"></i>
        <input v-model="form.mobile" name="mobile" :class="{err:errors[0]}" class="input" type="text" placeholder="绑定的手机号" />
      </div>
      <div class="error" v-if="errors[0]">{{errors[0]}}</div>
    </Field>
    <Field
      class="xtx-form-item"
      tag="div"
      v-slot="{errors}"
      rules="required|code"
      name="验证码"
      :detectInput="false"
    >
      <div class="field">
        <i class="icon iconfont icon-code"></i>
        <input v-model="form.code" name="code" :class="{err:errors[0]}" class="input" type="text" placeholder="短信验证码" />
        <span @click="send()" class="code">
          {{duration===0?'发送验证码':`${duration}秒后发送`}}
        </span>
      </div>
      <div class="error" v-if="errors[0]">{{errors[0]}}</div>
    </Field>
    <a @click="submit()" href="javascript:;" class="submit">立即绑定</a>
  </Form>
</template>

<script>
import { extend, ValidationProvider, ValidationObserver, configure } from 'vee-validate'
import { required } from 'vee-validate/dist/rules'
import { mapMutations, mapState } from 'vuex'
configure({ enent: 'blur' })
// 必填
extend('required', {
  ...required,
  message: '请输入{_field_}'
})
// 用户名
extend('username', {
  validate: async (value) => {
    // 校验格式
    if (value.length > 20) {
      return '用户名称是20个字以内'
    }
    // 校验是否存在
    const { data } = await this.$http.get(`register/check?username=${value}`)
    if (!data.result.valid) {
      return '用户名已存在，请换一个'
    }
    return true
  }
})
// 手机号
extend('mobile', {
  validate: (value) => {
    // 校验格式
    if (!/^1[3-9]\d{9}$/.test(value)) {
      return '手机号格式不正确'
    }
    return true
  }
})
// 手机号
extend('code', {
  validate: (value) => {
    // 校验格式
    if (!/^\d{6}$/.test(value)) {
      return '验证码6个数字'
    }
    return true
  }
})
// 密码
extend('password', {
  params: ['target'],
  validate: (value, { target }) => {
    // 校验格式
    if (!/^\w{6,20}$/.test(value)) {
      return '密码是6-20个字符'
    }
    if (value !== target) {
      return '两次输入的密码不一致'
    }
    return true
  }
})
export default {
  name: 'CallbackBind',
  components: { Form: ValidationObserver, Field: ValidationProvider },
  props: ['nickname', 'avatar', 'openId'],
  data () {
    return {
      form: {
        mobile: '',
        code: ''
      },
      duration: 0
    }
  },
  computed: {
    ...mapState('user', ['returnUrl'])
  },
  methods: {
    ...mapMutations('user', ['setUser']),
    async submit () {
      const valid = await this.$refs.form.validate()
      if (valid) {
        try {
          const { data } = await this.$http.post('/login/social/bind', { unionId: this.openId, ...this.form })
          this.setUser(data.result)
          this.$router.push(this.returnUrl || '/')
          this.$message({ message: '绑定账户成功', type: 'success' })
        } catch (e) {
          console.log(e)
          this.$message({ message: '绑定账户失败', type: 'error' })
        }
      }
    },
    async send () {
      const { valid } = await this.$refs.mobile.validate()
      if (valid === true) {
        if (this.duration > 0) return
        await this.$http.get('/login/social/code', { mobile: this.form.mobile })
        this.duration = 60
        clearInterval(this.timer)
        this.timer = window.setInterval(() => {
          this.duration--
          if (this.duration === 0) clearInterval(this.timer)
        }, 1000)
      }
    }
  }
}
</script>

<style scoped lang='less'>
// 表单
.xtx-form {
  padding: 50px 0;
  &-item {
    display: flex;
    align-items: center;
    width: 700px;
    margin: 0 auto;
    padding-bottom: 25px;
    .label {
      width: 180px;
      padding-right: 10px;
      text-align: right;
      color: #999;
      ~ .field {
        margin-left: 0;
      }
    }
    .field {
      width: 320px;
      height: 50px;
      position: relative;
      margin-left: 190px;
      .icon {
        position: absolute;
        left: 0;
        top: 0;
        width: 40px;
        height: 50px;
        text-align: center;
        line-height: 50px;
        color: #999;
        ~ .input {
          padding-left: 40px;
        }
      }
      .input{
        border: 1px solid #e4e4e4;
        width: 320px;
        height: 50px;
        line-height: 50px;
        padding: 0 10px;
        &.err {
          border-color: @priceColor;
        }
        &:focus,&:active{
          border-color: @xtxColor;
        }
      }
    }
    .error {
      width: 180px;
      padding-left: 10px;
      color: @priceColor;
    }
  }
  .submit {
    width: 320px;
    height: 50px;
    border-radius: 4px;
    background: @xtxColor;
    height: 50px;
    line-height: 50px;
    text-align: center;
    font-size: 16px;
    color: #fff;
    display: block;
    margin: 0 auto;
  }
}
.user-info {
    width: 320px;
    height: 70px;
    margin: 0 auto;
    display: flex;
    background: #f2f2f2;
    align-items: center;
    padding: 0 10px;
    margin-bottom: 25px;
    img {
      background: #f2f2f2;
      width: 50px;
      height: 50px;
    }
    p {
      padding-left: 10px;
    }
  }
  .code {
    position: absolute;
    right: 0;
    top: 0;
    line-height: 50px;
    width: 80px;
    color: #999;
    &:hover {
      cursor: pointer;
    }
  }
</style>
